package com.quzi.kettle.activitise;

import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.quzi.kettle.GlobalConfig;
import com.quzi.kettle.R;
import com.quzi.kettle.activitise.main.MyKettles;
import com.quzi.kettle.activitise.main.TempActivity;
import com.quzi.kettle.activitise.process.BindKettleActivity;
import com.quzi.kettle.easylink.FirstTimeConfig2;
import com.quzi.kettle.easylink.FirstTimeConfigListener;
import com.quzi.kettle.easylink.utils.EasyLinkConstants;
import com.quzi.kettle.easylink.utils.EasyLinkDialogManager;
import com.quzi.kettle.easylink.utils.EasyLinkUtils;
import com.quzi.kettle.easylink.utils.EasyLinkWifiManager;
import com.quzi.kettle.socket.UdpReceive;
import com.quzi.kettle.view.TitleBarHandler;
import com.quzi.kettle.view.TitleBarView;

public class EasyLink extends BaseActivity implements OnClickListener,
		FirstTimeConfigListener, OnCheckedChangeListener, TextWatcher {

	private EasyLinkWifiManager mWifiManager = null;

	private Button mSendDataPackets_2 = null;

	private EditText mSSIDInputField = null;

	private EditText mPasswordInputField = null;

	private TextView mGateWayIPInputField = null;

	public static EditText mDeviceNameInputField = null;

	private EasyLinkDialogManager mDialogManager = null;

	// private ProgressBar mconfigProgress_2 = null;

	private Timer timer = new Timer();

	public static boolean sIsNetworkAlertVisible = false;

	/**
	 * Boolean to check if network is enabled or not
	 */
	public boolean isNetworkConnecting = false;

	private boolean flag = true;

	/**
	 * Dialog ID to tigger no network dialog
	 */
	private static final int NO_NETWORK_DIALOG_ID = 002;

	private UdpReceive udpReceive = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/**
		 * Disable orientation if launched in mobile
		 */
		EasyLinkUtils.setProtraitOrientationEnabled(EasyLink.this);

		setContentView(R.layout.configration);

		/**
		 * Check for WIFI intially
		 */
		if (isNetworkConnecting) {

		} else {
			if (!sIsNetworkAlertVisible) {
				checkNetwork("ONCREATE");
			}
		}

		initViews();

		setViewClickListeners();

		initData();

		timerDelayForAPUpdate();

		initTitleBar();

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
		intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
		registerReceiver(broadcastReceiver, intentFilter);
	}

	TitleBarView titleView;

	protected void initTitleBar() {
		super.initTitleBar();
		titleView = (TitleBarView) findViewById(R.id.titleview);
		titleView.setTitle(getResources().getString(R.string.config));

		titleView.setTitleBarClickListener(new TitleBarHandler() {

			@Override
			public void ClickRight() {
			}

			@Override
			public void ClickLeft() {
				if (deviceList.size() == 0) {
					nextActivity(TempActivity.class);
				} else {
					finish();
				}

				//
			}
		});
	}

	public EasyLinkWifiManager getWiFiManagerInstance() {
		if (mWifiManager == null) {
			mWifiManager = new EasyLinkWifiManager(EasyLink.this);
		}
		return mWifiManager;
	}

	private void initData() {

		if (getWiFiManagerInstance().getCurrentSSID() != null
				&& getWiFiManagerInstance().getCurrentSSID().length() > 0) {
			mSSIDInputField.setText(getWiFiManagerInstance().getCurrentSSID());

			mSSIDInputField.setEnabled(false);
			mSSIDInputField.setFocusable(false);
			mSSIDInputField.setFocusableInTouchMode(false);
		}

		mGateWayIPInputField.setText(getWiFiManagerInstance()
				.getGatewayIpAddress());
	}

	private boolean checkNetwork(String str) {

		if (!(getWiFiManagerInstance().isWifiConnected())) {
			sIsNetworkAlertVisible = true;
			mDialogManager = new EasyLinkDialogManager(EasyLink.this);
			showDialog(NO_NETWORK_DIALOG_ID);
			return false;
			// Do stuff when wifi not there.. disable start button.
		} else {
			return true;
		}

	}

	/**
	 * Initialise all view components from xml
	 */
	private void initViews() {

		mSendDataPackets_2 = (Button) findViewById(R.id.config_start_button_2);

		mSSIDInputField = (EditText) findViewById(R.id.config_ssid_input);
		mPasswordInputField = (EditText) findViewById(R.id.config_passwd_input);
		mGateWayIPInputField = (TextView) findViewById(R.id.config_gateway_input);
		// mKeyInputField = (EditText) findViewById(R.id.config_key_input);
		mDeviceNameInputField = (EditText) findViewById(R.id.config_device_name_input);

		// mconfigProgress_2 = (ProgressBar)
		// findViewById(R.id.config_progress_2);
		// mconfigProgress_2.bringToFront();

	}

	/**
	 * Init the click listeners of all required views
	 */
	private void setViewClickListeners() {

		mSendDataPackets_2.setOnClickListener(this);

	}

	private boolean ifListContainTopic() {
		for (int i = 0; i < deviceList.size(); i++) {
			if (deviceList.get(i).getMain_mac().equals(GlobalConfig.topic)) {
				return true;
			}
		}
		return false;

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.config_start_button_2:
			// Check network
			if (checkNetwork("bUTTON")) {
				if (!ifListContainTopic()) {
					GlobalConfig.topic = "";
				}

				try {

					sendPacketData2();
					getUdpReceive().start();
					showLoadingDialogWithTimeOut();
					handler.sendEmptyMessageDelayed(TIMEOUT, 30000);

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("mmqtt", "onCLick exception" + e);
				}
			}
			break;
		}
	}

	private UdpReceive getUdpReceive() {

		// if (udpReceive == null) {
		// udpReceive = UdpReceive.getInstance(handler, true);
		// }
		// return udpReceive;
		udpReceive = null;
		udpReceive = new UdpReceive(handler, true);
		return udpReceive;
	}

	private FirstTimeConfig2 firstConfig2 = null;

	public boolean isCalled2 = false;

	private void sendPacketData2() throws Exception {
		// handler.sendEmptyMessageDelayed(TIMEOUT, 2000000);
		if (!isCalled2) {
			isCalled2 = true;
			// mSendDataPackets_2.setText("停      止");
			try {
				firstConfig2 = getFirstTimeConfigInstance2(EasyLink.this);
			} catch (Exception e) {
				e.printStackTrace();
			}

			firstConfig2.transmitSettings();

		} else {
			if (firstConfig2 != null) {
				stopPacketData2();
			}
		}
		// mSendDataPackets_2
		// .setBackgroundResource(R.drawable.selection_focus_btn);
		// mconfigProgress_2.setVisibility(ProgressBar.VISIBLE);
		// } else {
		// if (firstConfig2 != null) {
		// stopPacketData2();
		// }
		// }
	}

	private void stopPacketData2() {

		if (isCalled2) {
			try {
				isCalled2 = false;

				mSendDataPackets_2.setText(getResources().getString(
						R.string.start_label_2));

				firstConfig2.stopTransmitting();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private FirstTimeConfig2 getFirstTimeConfigInstance2(
			FirstTimeConfigListener apiListener) throws Exception {
		String ssidFieldTxt = mSSIDInputField.getText().toString().trim();
		String passwdText = mPasswordInputField.getText().toString().trim();
		String deviceInput = mDeviceNameInputField.getText().toString().trim();
		if (deviceInput.length() == 0) {
			deviceInput = "EMW3161";
		}

		byte[] totalBytes = null;
		String keyInput = null;

		return new FirstTimeConfig2(apiListener, passwdText, totalBytes,
				getWiFiManagerInstance().getGatewayIpAddress(), ssidFieldTxt,
				deviceInput);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (!(EasyLinkUtils.isScreenXLarge(getApplicationContext()))) {
			return;
		}
	}

	@Override
	public void onFirstTimeConfigEvent(FtcEvent arg0, Exception arg1) {
		Log.d("mmqtt", "onFirstTimeConfig");
		try {

			arg1.printStackTrace();
			Log.d("mmqtt", " " + arg1);
		} catch (Exception e) {
			e.printStackTrace();
		}

		switch (arg0) {
		case FTC_ERROR:
			handler.sendEmptyMessage(EasyLinkConstants.DLG_CONNECTION_FAILURE);
			break;
		case FTC_SUCCESS:
			handler.sendEmptyMessage(EasyLinkConstants.DLG_CONNECTION_SUCCESS);
			break;
		case FTC_TIMEOUT:
			handler.sendEmptyMessage(EasyLinkConstants.DLG_CONNECTION_TIMEOUT);
			break;
		default:
			break;
		}
	}

	private void showConnectionTimedOut(int dialogType) {
		if (mDialogManager == null) {
			mDialogManager = new EasyLinkDialogManager(EasyLink.this);
		}
		mDialogManager.showCustomAlertDialog(dialogType);
	}

	private void showFailureAlert(int dialogType) {
		if (mDialogManager == null) {
			mDialogManager = new EasyLinkDialogManager(EasyLink.this);
		}
		mDialogManager.showCustomAlertDialog(dialogType);
	}

	private void showConnectionSuccess(int dialogType) {
		if (mDialogManager == null) {
			mDialogManager = new EasyLinkDialogManager(EasyLink.this);
		}
		mDialogManager.showCustomAlertDialog(dialogType);
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (!sIsNetworkAlertVisible) {
			if (isNetworkConnecting) {

			} else {
				if (!(getWiFiManagerInstance().isWifiConnected())) {
					showDialog(NO_NETWORK_DIALOG_ID);
				}
			}
			sIsNetworkAlertVisible = false;
		}
	}

	/**
	 * Stop data trasnfer on app exist if is running
	 */
	@Override
	protected void onStop() {
		super.onStop();

		stopPacketData2();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	private boolean isKeyChecked = false;

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		isKeyChecked = isChecked;

	}

	@Override
	public void afterTextChanged(Editable s) {
		// overriden method for text changed listener
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// overriden method for text changed listener
	}

	int textCount = 0;

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	public static final int HAVEADD = 100;
	public static final int ToastMsg = 99;
	public static final int BIND_DEVICE = 98;
	public static final int TIMEOUT = 97;
	/**
	 * Handler class for invoking dialog when a thread notifies of FTC_SUCCESS
	 * or FTC_FAILURE
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case TIMEOUT:
				if (isShowingDialog()) {
					disLoadingDialogWithTimeOut();
				}
				Toast.makeText(getApplicationContext(), "绑定超时了",
						Toast.LENGTH_SHORT).show();
				break;
			case BIND_DEVICE:
				if (isShowingDialog()) {
					disLoadingDialogWithTimeOut();
				}

				handler.removeMessages(TIMEOUT);
				nextActivity(BindKettleActivity.class);
				finish();
				break;
			case HAVEADD:
				if (isShowingDialog()) {
					disLoadingDialogWithTimeOut();
				}
				Toast.makeText(getApplicationContext(), (String) msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			case ToastMsg:
				Toast.makeText(getApplicationContext(), (String) msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			// case 1:
			// stopPacketData2();
			// handler.removeMessages(TIMEOUT);
			// Bundle data = msg.getData();
			// String result = data.getString("result");
			// Intent intent = new Intent();
			// intent.putExtra(GlobalConfig.UDPRESULT, result);
			// setResult(RESULT_OK, intent);
			// Intent intent2 = new Intent(EasyLink.this,
			// MainActivityTest.class);
			// startActivity(intent2);
			// finish();
			//
			// break;
			case EasyLinkConstants.DLG_CONNECTION_FAILURE:
				showFailureAlert(EasyLinkConstants.DLG_CONNECTION_FAILURE);
				break;
			case EasyLinkConstants.DLG_CONNECTION_SUCCESS:
				showConnectionSuccess(EasyLinkConstants.DLG_CONNECTION_SUCCESS);
				handler.sendEmptyMessage(BIND_DEVICE);
				break;

			case EasyLinkConstants.DLG_CONNECTION_TIMEOUT:
				showConnectionTimedOut(EasyLinkConstants.DLG_CONNECTION_TIMEOUT);
				break;
			}
			/**
			 * Stop transmission
			 */
			// stopPacketData2();
			stopPacketData2();
		}
	};

	/**
	 * 点击返回按键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {// 如果按下的是回退健
			// 表示按下回退键且不是常按
			if (event.getAction() == KeyEvent.ACTION_DOWN
					&& event.getRepeatCount() == 0) {
				if (deviceList.size() == 0) {
					nextActivity(TempActivity.class);
				} else {
					nextActivity(MyKettles.class);
				}
				// 调用上面写的退出

				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * Timer to check network periodically at some time intervals. If network is
	 * available then the current access point details are set to the SSID field
	 * in next case else a alert dialog is shown
	 */
	void timerDelayForAPUpdate() {
		int periodicDelay = 1000; // delay for 1 sec.
		int timeInterval = 180000; // repeat every 3minutes.

		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				runOnUiThread(new Runnable() {
					public void run() {
						// stuff that updates ui
						if (!sIsNetworkAlertVisible) {
							if (!(getWiFiManagerInstance().isWifiConnected())) {
								showDialog(NO_NETWORK_DIALOG_ID);
							}
						}
					}
				});
			}
		}, periodicDelay, timeInterval);
	}

	/**
	 * Called when activity is no more visible to user and the activity is
	 * removed from stack
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();

		timer.cancel();
		unregisterReceiver(broadcastReceiver);
	}

	/**
	 * Common Alert dialog instance to show no network or AP change message
	 */
	private AlertDialog alert = null;

	/**
	 * Dialog creation is done here
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder1;
		try {

			if (alert != null) {
				if (alert.isShowing()) {
					alert.dismiss();
				}
			}
		} catch (Exception e) {

		}

		switch (id) {
		case NO_NETWORK_DIALOG_ID:
			sIsNetworkAlertVisible = true;
			builder1 = new AlertDialog.Builder(this);
			builder1.setCancelable(true)
					.setTitle(
							getResources().getString(
									R.string.alert_easylink_title))
					.setMessage(
							getResources().getString(
									R.string.alert_no_network_title))
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									sIsNetworkAlertVisible = false;

								}
							});

			alert = builder1.create();
			alert.show();
			break;
		}
		return super.onCreateDialog(id);
	}

	/**
	 * A broadcast reciever which is registered to notify the app about the
	 * changes in network or Access point is switched by the Device WIfimanager
	 */
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
				if (intent.getBooleanExtra(
						WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {

				} else {
					// wifi connection was lost
					if (!sIsNetworkAlertVisible) {
						if (!(getWiFiManagerInstance().isWifiConnected())) {

						}
					}
					/**
					 * Clearing the previous SSID Gateway ip if accesspoint is
					 * disconnected in between connection or usage
					 */
					mSSIDInputField.setText("");
					mGateWayIPInputField.setText("");
				}
			}

			if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {

				NetworkInfo info = intent
						.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
				if (info.getType() == ConnectivityManager.TYPE_WIFI) {

				}

				if (info.getDetailedState() == DetailedState.CONNECTED) {
					isNetworkConnecting = true;
					WifiManager myWifiManager = (WifiManager) context
							.getSystemService(Context.WIFI_SERVICE);
					WifiInfo wifiInfo = myWifiManager.getConnectionInfo();
					mSSIDInputField.setText(EasyLinkWifiManager
							.removeSSIDQuotes(wifiInfo.getSSID()));
					mSSIDInputField.setEnabled(false);
					mSSIDInputField.setFocusable(false);
					mSSIDInputField.setFocusableInTouchMode(false);
					int gatwayVal = myWifiManager.getDhcpInfo().gateway;
					String gateWayIP = (String.format("%d.%d.%d.%d",
							(gatwayVal & 0xff), (gatwayVal >> 8 & 0xff),
							(gatwayVal >> 16 & 0xff), (gatwayVal >> 24 & 0xff)))
							.toString();

					mGateWayIPInputField.setText(gateWayIP);
				}
			}
		}
	};

}